package ldh.im.fxgui;

import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import ldh.im.fxbase.util.DbUtil;
import ldh.im.fxbase.util.LoggerUtil;
import ldh.im.fxgui.controller.LoginController;
import ldh.im.fxgui.controller.MainController;
import ldh.im.fxbase.help.ResizeHelper;
import ldh.im.fxbase.util.RegionUtil;
import ldh.im.fxbase.util.StageUtil;
import ldh.im.fxgui.util.UiUtil;

import java.io.File;
import java.nio.file.Files;
import java.sql.SQLException;
import java.util.logging.Logger;

public class MainApp extends TrayApplication {

    private static final Logger LOGGER = LoggerUtil.getFileLogger(MainApp.class);
    private Pane mainPane = null;

    @Override
    public void startPane(Stage primaryStage) {
        checkDb();
        mainPane = buildApp();
        showLoginPane(primaryStage);
    }

    public void startMainStage(Stage primaryStage) {
        primaryStage.getIcons().add(new Image(this.getClass().getResource("/imgs/icon.jpg").toExternalForm()));

        Scene scene = new Scene(mainPane, 900, 600);
        scene.setFill(null);
        scene.getStylesheets().add(this.getClass().getResource("/css/login.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/var.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/stage.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/main.css").toExternalForm());
//        scene.getStylesheets().add(this.getClass().getResource("/css/scrollbar.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/window-scrollbar.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/tabpane.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/bootstrapfx.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.initStyle(StageStyle.TRANSPARENT);

        ResizeHelper.addResizeListener(primaryStage);
        primaryStage.show();
        primaryStage.toFront();
    }

    private Pane buildApp() {
        RegionUtil.FxmlBean<Pane, MainController> fxmlBean = RegionUtil.loadFxmlBean(MainApp.class.getResource("/fxml/MainPage.fxml"));
        UiUtil.setMainController(fxmlBean.getController());
        UiUtil.getEmojiPane();  // 提前实例化
        return fxmlBean.getNode();
    }

    private void showMainPane() {
        startMainStage(StageUtil.getStage());

        if (StageUtil.isSupportTray()) {
            enableTray(StageUtil.getStage());
        }
    }

    private void showLoginPane(Stage primaryStage) {
        RegionUtil.FxmlBean<Pane, LoginController> fxmlBean = RegionUtil.loadFxmlBean(MainApp.class.getResource("/fxml/LoginPage.fxml"));
        Scene scene = fxmlBean.getController().createScene();

        Stage stage = new Stage();
        stage.getIcons().add(new Image(this.getClass().getResource("/imgs/icon.jpg").toExternalForm()));

        stage.initOwner(primaryStage);
        stage.initStyle(StageStyle.TRANSPARENT);
        stage.setScene(scene);

        stage.show();

        fxmlBean.getController().setLoginStage(stage);
        fxmlBean.getController().setConsumer((Void)-> {
            showMainPane();
        });
    }

    private void checkDb() {
        try {
            String file = UiUtil.getDataFile(File.separator + "data" + File.separator + "db" + File.separator + "im.mv.db");
            LOGGER.info("check db is installed! file:" + file);
            File f = new File(file);
            if (!f.exists()) {
                String sqlFile = UiUtil.getDataFile(File.separator + "doc" + File.separator + "client" + File.separator + "imgui-h2.sql");
                LOGGER.info("install h2 db:" + file + ",sqlFile: " + sqlFile);
                initSql(sqlFile);
            }
            checkChangeSql();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int initSql(String sqlFile) throws SQLException {
        return DbUtil.transaction((queryRunner, connection) -> {
            String sql = getImSql(sqlFile);
            LOGGER.info("handel sql: " + sql);
            int num = queryRunner.execute(connection, sql);
            return num;
        });
    }

    private void checkChangeSql() {
        try {
            String sqlFile = UiUtil.getDataFile(File.separator + "doc" + File.separator + "client" + File.separator + "imgui-ch.sql");
            File f = new File(sqlFile);
            if (f.exists()) {
                initSql(sqlFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getImSql(String sqlFile) {
        String sql = "";
        try {
            sql = Files.readString(new File(sqlFile).toPath());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sql;
    }
}
